package com.mldong.modules.sys.handler;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.log.Log;
import com.mldong.auth.handler.RelThirdAccountHandler;
import com.mldong.auth.handler.RelThirdAccountModel;
import com.mldong.consts.CommonConstant;
import com.mldong.exception.ServiceException;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 微信授权关联处理类
 * @author mldong
 * @date 2024/8/19
 */
@Component
public class RelWxMaHandler implements RelThirdAccountHandler {
    private static final Log log = Log.get();
    @Override
    public List<RelThirdAccountModel> relHandle(Dict dict) {
        List<RelThirdAccountModel> relThirdAccountModelList = new ArrayList<>();
        String code = dict.getStr("code");
        WxMaService wxMaService = SpringUtil.getBean(WxMaService.class);
        WxMaJscode2SessionResult wxMaJscode2SessionResult = null;
        try {
            wxMaJscode2SessionResult = wxMaService.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            log.error(e);
            throw new ServiceException(10041001,"微信授权登录异常");
        }
        String openid = wxMaJscode2SessionResult.getOpenid();
        String unionid = wxMaJscode2SessionResult.getUnionid();
        if(ObjectUtil.isNotEmpty(openid)) {
            RelThirdAccountModel openidAccount = new RelThirdAccountModel();
            openidAccount.setThirdAccount(openid);
            openidAccount.setThirdType(CommonConstant.WX_OPENID);
            relThirdAccountModelList.add(openidAccount);
        }
        if(ObjectUtil.isNotEmpty(unionid)) {
            RelThirdAccountModel unionidAccount = new RelThirdAccountModel();
            unionidAccount.setThirdAccount(unionid);
            unionidAccount.setThirdType(CommonConstant.WX_UNIONID);
            relThirdAccountModelList.add(unionidAccount);
        }
        return relThirdAccountModelList;
    }

    @Override
    public List<String> unRelHandle(Dict dict) {
        return CollectionUtil.newArrayList(CommonConstant.WX_OPENID,CommonConstant.WX_UNIONID);
    }
}
